﻿using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;

namespace ICodeShare.UI.Converters
{
    [ValueConversion(typeof(Thickness), typeof(double))]
    public sealed class ThicknessToDoubleConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (!(value is Thickness))
            {
                return DependencyProperty.UnsetValue;
            }

            var thickness = (Thickness)value;
        
            var propertyName = parameter as string;
            if (parameter != null)
            {
                switch (propertyName.Trim().ToLower())
                {
                    case "left":
                        return thickness.Left;
                    case "top":
                        return thickness.Top;
                    case "right":
                        return thickness.Right;
                    case "bottom":
                        return thickness.Bottom;
                    default:
                        return (thickness.Left + thickness.Top + thickness.Bottom + thickness.Right) / 4;
                }
            }

            return (thickness.Left + thickness.Top + thickness.Bottom + thickness.Right) / 4;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (!(value is double))
            {
                return DependencyProperty.UnsetValue;
            }
            var source = (double)value;
            var parameters = parameter as string;
            if (parameters != null)
            {
                var thickness = new Thickness(0);
                switch (parameters.Trim().ToLower())
                {
                    case "left":
                        thickness.Left = source;
                        break;
                    case "top":
                        thickness.Top = source;
                        break;
                    case "right":
                        thickness.Right = source;
                        break;
                    case "bottom":
                        thickness.Bottom = source;
                        break;
                    default:
                        thickness = new Thickness(source, source, source, source);
                        break;
                }
                return thickness;
            }
            return new Thickness(source,source,source,source);
        }
    }
}
